<template>
  <div class="pagintion">
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="pageSizes"
      :layout="layout"
      :small="small"
      :background="background"
      :disabled="disabled"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :total="Math.max(total, 1)"
    />
  </div>
</template>

<script setup>
import { ref, watch } from "vue";
import { ElPagination } from "element-plus";

const props = defineProps({
  currentPage: {
    type: Number,
    default: 1,
  },
  pageSize: {
    type: Number,
    default: 10,
  },
  total: {
    type: Number,
    required: true,
  },
  pageSizes: {
    type: Array,
    default: () => [10, 20, 50, 100],
  },
  layout: {
    type: String,
    default: "total, sizes, prev, pager, next, jumper",
  },
  small: {
    type: Boolean,
    default: false,
  },
  background: {
    type: Boolean,
    default: false,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits([
  "update:currentPage",
  "update:pageSize",
  "pagination-change",
]);

// 使用 ref 来管理内部状态，并与 props 同步
const currentPage = ref(props.currentPage);
const pageSize = ref(props.pageSize);

// 监听 props 的变化，同步到内部状态
watch(
  () => props.currentPage,
  (newVal) => {
    currentPage.value = newVal;
  }
);
watch(
  () => props.pageSize,
  (newVal) => {
    pageSize.value = newVal;
  }
);

const handleSizeChange = (val) => {
  emit("update:pageSize", val);
  // 触发一个自定义事件，方便父组件统一处理
  emit("pagination-change", { currentPage: currentPage.value, pageSize: val });
};

const handleCurrentChange = (val) => {
  emit("update:currentPage", val);
  // 触发一个自定义事件，方便父组件统一处理
  emit("pagination-change", { currentPage: val, pageSize: pageSize.value });
};
</script>

<style scoped lang="less">
.pagintion {
  text-align: left;
  margin-top: 25px;
}
</style>
